package main

import (
	"github.com/gin-gonic/gin"
	"github.com/gookit/color"
	"github.com/spf13/cobra"
	"net"
	"net/http"
	"os"
)

type ProPath struct {
	Http  string `json:"http"`
	Local string `json:"local"`
	Port  string `json:"port"`
}

var pp = ProPath{}
var appCmd = &cobra.Command{
	Use:   "app",
	Short: "应用相关命令",
	RunE: func(cmd *cobra.Command, args []string) error {
		engine := gin.Default()
		engine.StaticFS(pp.Http, gin.Dir(pp.Local, true))
		engine.Any("/status", func(context *gin.Context) {
			context.JSONP(200, "ok")
		})
		var tcpItem string = "tcp4"
		server := &http.Server{
			Addr:    "0.0.0.0:" + pp.Port,
			Handler: engine,
		}
		color.Greenln("Server Start:", server.Addr)
		ln, err := net.Listen(tcpItem, server.Addr)
		if err != nil {
			color.Greenln(server.Addr, err)
			panic(err)
		}
		if err := server.Serve(ln.(*net.TCPListener)); err != nil {
			panic(err)
		}
		return nil
	},
}

func init() {
	getwd, err := os.Getwd()
	if err != nil {
		panic(err)
	}
	appCmd.Flags().StringVarP(&pp.Http, "http url", "u", "/File", "请求路径")
	appCmd.Flags().StringVarP(&pp.Local, "local filepath", "l", getwd, "本地路径 pwd")
	appCmd.Flags().StringVarP(&pp.Port, "server port", "p", "8080", "端口")
}

func main() {
	err := appCmd.Execute()
	if err != nil {
		panic(err)
	}
}
